
import Page from '@/components/Layout'
import { getFootballAnalysis, getFootballStatistics, getFootballIndexSum, getBasketballDetail, getBasketballAnalysis, getBasketballIndexSum } from '@/server/live'
import { useSafeState } from 'ahooks'
import dayjs from 'dayjs'
import styles from './styles.module.scss'
import { RiseOutlined, FallOutlined } from "@ant-design/icons";
import { Select } from 'antd';
import { useMemo } from 'react'
import RenderJudge from '@/components/RenderJudge'
import Head from 'next/head'
const fState = {
  0: "比赛异常",
  1: "未开赛",
  2: "上半场",
  3: "中场",
  4: "下半场",
  5: "加时赛",
  6: "加时赛",
  7: "点球决战",
  8: "完场",
  9: "推迟",
  10: "中断",
  11: "腰斩",
  12: "取消",
  13: "待定"
}

const bState = {
  0: "比赛异常",
  1: "未开赛",
  2: "第一节",
  3: "第一节完",
  4: "第二节",
  5: "第二节完",
  6: "第三节",
  7: "第三节完",
  8: "第四节",
  9: "加时",
  10: "完场",
  11: "中断",
  12: "取消",
  13: "延期",
  14: "腰斩",
  15: "待定"
}


const HistoryPanner = ({ info, teamMatch, value }) => {
  const [size, setSize] = useSafeState(5)
  const [align, setAlign] = useSafeState(0)
  const [match, setMatch] = useSafeState('')
  const teamMatchList = useMemo(() => {

    let showSizeData = [...(teamMatch || [])]?.slice(0, size)
    if (align === 1) {
      //筛选主场
      showSizeData = showSizeData?.filter(v => v?.homeTeamId === info?.home_team?.id)
    }
    if (align === 2) {
      //筛选客
      showSizeData = showSizeData?.filter(v => v?.awayTeamId === info?.away_team?.id)
    }

    if (match > 0) {
      //
      showSizeData = showSizeData?.filter(v => v?.eventId === match)
    }


    return showSizeData

  }, [teamMatch, size, align, match, info])


  const eventIds = useMemo(() => {
    const ids = teamMatch?.reduce((sum, current) => {
      if (sum?.findIndex(row => row?.eventId === current?.eventId) > -1) return sum
      return [...sum, current]
    }, [])
    return ids
  }, [teamMatch])

  const Result = ({ row }) => {
    if (row?.homeTeamScore > row?.awayTeamScore) {
      return <em style={{ color: 'red' }}>赢</em>
    }
    if (row?.homeTeamScore < row?.awayTeamScore) {
      return <em style={{ color: "var(--theme)" }}>负</em>
    }

    if (row?.homeTeamScore === row?.awayTeamScore) {
      return <em style={{ color: "#3C51BF" }}>平</em>
    }
    return <></>
  }

  const Trend = ({ row }) => {
    // row?.homeTeamScore > row?.awayTeamScore
    const rata = Number(row?.rate)
    if (row?.homeTeamScore > (row?.awayTeamScore + rata)) return <em style={{ color: 'red' }}>赢</em>
    if (row?.homeTeamScore < (row?.awayTeamScore + rata)) return <em style={{ color: "var(--theme)" }}>输</em>
    if (row?.homeTeamScore === (row?.awayTeamScore + rata)) return <em style={{ color: "#3C51BF" }}>走</em>
    return <></>
  }


  const NumberGoals = ({ row }) => {
    const zf = Number(row?.zf)
    if ((row?.homeTeamScore + row?.awayTeamScore) > zf) return <em style={{ color: 'red' }}>大</em>
    if ((row?.homeTeamScore + row?.awayTeamScore) < zf) return <em style={{ color: "var(--theme)" }}>小</em>
    if ((row?.homeTeamScore + row?.awayTeamScore) === zf) return <em style={{ color: "#3C51BF" }}>走</em>
    return <></>
  }
  return (

    <aside style={{ minHeight: 362 }}>
      <header>
        <img src={info?.[`${value}_team`]?.logo || info?.[`${value}TeamLogo`]} alt="" />
        <span>{info?.[`${value}_team`]?.name_zh || info?.[`${value}TeamName`]}</span>


        <Select defaultValue={5} style={{ width: 70 }} onChange={(v) => setSize(v)}>
          <Select.Option value={5}>5场</Select.Option>
          <Select.Option value={10}>10场</Select.Option>
          <Select.Option value={15}>15场</Select.Option>
        </Select>


        <Select defaultValue={0} style={{ width: 70, margin: "0 20px" }} onChange={(v) => setAlign(v)}>
          <Select.Option value={0}>全部</Select.Option>
          <Select.Option value={1}>主场</Select.Option>
          <Select.Option value={2}>客场</Select.Option>
        </Select>


        <Select defaultValue={0} style={{ width: 100 }} placeholder="赛事选择" onChange={(v) => setMatch(v)}>
          <Select.Option value={0}>全部</Select.Option>
          {
            eventIds?.map(row => (
              <Select.Option value={row?.eventId} key={row?.eventId}>{row?.eventName}</Select.Option>
            ))
          }
        </Select>
      </header>
      <table cellspacing={10} cellpadding={10} align='center' className={styles.history}>
        <tr className={styles.header}>
          <th>赛事</th>
          <th>比赛日期</th>
          <th>
            <span>主队</span>
            <span style={{ margin: "0 8px" }}>比分</span>
            <span>客队</span>
          </th>
          <th>半场</th>
          <th>胜负</th>
          <th>走势</th>
          <th>进球数</th>
        </tr>
        {
          teamMatchList?.map(row => (
            <tr key={row?.eventId}>
              <td>{row?.eventName}</td>
              <td>{row?.date}</td>
              <td className={styles.center}>
                <span>{row?.homeTeamName}</span>
                <em>
                  <i>{row?.homeTeamScore}</i>
                  <i>:</i>
                  <i>{row?.awayTeamScore}</i>
                </em>
                <span>{row?.awayTeamName}</span>
              </td>
              <td>
                <span>
                  {row?.homeTeamHalf}
                </span>
                <em>:</em>
                <span>
                  {row?.awayTeamHalf}
                </span>
              </td>
              <td>
                <Result row={row}></Result>
              </td>
              <td>
                <Trend row={row}></Trend>
              </td>
              <td>
                <NumberGoals row={row}></NumberGoals>
              </td>
            </tr>
          ))
        }
        {/* <tr>
                  <td>总</td>
                  <TD row={match?.homeIntegrate}></TD>
                </tr> */}
      </table>
    </aside>
  )
}


const Exponent = ({ style, indexSum, type }) => {

  const sum = (game, index) => {
    if (type === '1') return Math.floor((1 / game[index]) / ((1 / game[0]) + (1 / game[1]) + (1 / game[2])) * 100) + '%'
    return Math.floor((1 / game[index]) / ((1 / game[0]) + (1 / game[1])) * 100) + '%'
  }
  const backSum = (game) => {
    if (type === '1') return Math.floor((game[0] * game[1] * game[2]) / (game[0] * game[1] + game[1] * game[2] + game[0] * game[2]) * 100) + '%'
    return Math.floor(1 / ((1 / game[1]) + (1 / game[0])) * 100) + '%'
  }

  const averageValue = (game, index) => {
    // index 0 主 1 平 2 客
    const length = indexSum?.eu?.company?.length
    if (type === '1') {
      const all = indexSum?.eu?.company?.reduce((s, curr) => {
        const value = curr?.inGame?.length > 0 ? curr?.inGame : curr?.last
        const k = (1 / value[index]) / ((1 / value[0]) + (1 / value[1]) + (1 / value[2])) //
        return s + k
      }, 0)

      return Math.floor(game[index] * (all / length) * 100) / 100
    }

    if (type === '2') {
      const all = indexSum?.eu?.company?.reduce((s, curr) => {
        const value = curr?.inGame?.length > 0 ? curr?.inGame : curr?.last
        const k = (1 / value[index]) / ((1 / value[0]) + (1 / value[1])) //
        return s + k
      }, 0)
      return Math.floor(game[index] * (all / length) * 100) / 100
    }
    return '-'
  }


  const renderLength = type === '1' ? 3 : 2 //足球有胜平负 篮球 只有 胜负

  const TD = ({ row }) => {
    const show = row?.inGame?.length > 0 ? row?.inGame : row?.last
    console.log(row)
    return (
      <tr>
        <td>{row?.company}</td>
        {
          show?.map((item, index) => {
            const color = () => {
              const fv = row?.first[index]
              if (item > fv) return 'red'
              if (item === fv) return 'var(--font333)'
              if (item < fv) return 'var(--theme)'
              return 'var(--font333)'
            }

            const arraw = () => {
              const fv = row?.first[index]
              if (item > fv) return <RiseOutlined style={{ color: "red" }} />
              if (item === fv) return <></>
              if (item < fv) return <FallOutlined style={{ color: "var(--theme)" }} />
              return <></>
            }

            return (
              <>
                <td key={index} style={{ color: color() }}>
                  <span>{item || 0}</span>
                  {arraw()}
                </td>
              </>
            )
          })
        }
        {
          Array.from({ length: renderLength })?.map((item, index) => (
            <td key={index}>
              {
                sum(show, index)
              }
            </td>
          ))
        }

        <td>
          {backSum(show)}
        </td>

        {
          Array.from({ length: renderLength })?.map((item, index) => (
            <td key={index}>
              {
                averageValue(show, index)
              }
            </td>
          ))
        }
      </tr>
    )
  }


  return (
    <section style={style} className={styles.indexSum}>
      <table className={type === '1' ? styles.type1 : styles.type2}>
        <tr>
          <th>公司</th>
          <th>主胜</th>
          <RenderJudge value={type === '1'} active={
            <th>和</th>
          } />

          <th>客胜</th>
          <th>主胜率</th>
          <RenderJudge value={type === '1'} active={
            <th>和率</th>
          } />
          <th>客胜率</th>
          <th>返还率</th>
          <th colspan="3">凯利走势</th>
        </tr>
        {
          indexSum?.eu?.company?.map((row, index) => (
            <TD row={row} key={index}></TD>
          ))
        }
      </table>
    </section>
  )
}


const AnalysisPanner = ({ info, match, style, type }) => {
  return (
    <RenderJudge value={type === '1'} active={
      <RankingFootball match={match} info={info} style={style} />
    } inactive={
      <RankingBasketball match={match} info={info} style={style} />
    } />
  )
}


const RankingFootball = ({ info, match, style, }) => {
  const TD = ({ row }) => {

    return (
      <>
        <td>{row?.played || '-'}</td>
        <td>{row?.won || '-'}</td>
        <td>{row?.drawn || ''}</td>
        <td>{row?.lost || '-'}</td>
        <td>{row?.goals || '-'}</td>
        <td>{row?.against || '-'}</td>
        <td>{row?.diff || '-'}</td>
        <td>{row?.pts || '-'}</td>
        <td>{row?.position || '-'}</td>
        <td>{Math.floor(((row?.won / row?.played) || 0) * 100) + "%"}</td>
      </>
    )
  }

  return (
    <section style={{ ...style, }}>
      <aside>
        <p>联赛积分</p>
        <section >
          <aside style={{ minHeight: 260 }}>
            <header>
              <img src={info?.home_team?.logo} alt="" />
              <span>{info?.home_team?.name_zh}</span>
            </header>
            <table cellspacing={10} cellpadding={10} align='center'>
              <tr className={styles.header}>
                <th>全场</th>
                <th>赛</th>
                <th>胜</th>
                <th>平</th>
                <th>负</th>
                <th>得</th>
                <th>失</th>
                <th>净</th>
                <th>得分</th>
                <th>排名</th>
                <th>胜率</th>
              </tr>
              <tr>
                <td>总</td>
                <TD row={match?.homeIntegrate}></TD>
              </tr>
              <tr>
                <td>主</td>
                <TD row={match?.homeIntegrateInfo?.home}></TD>
              </tr>
              <tr>
                <td>客</td>
                <TD row={match?.homeIntegrateInfo?.away}></TD>
              </tr>
            </table>
          </aside>
          <aside style={{ minHeight: 260 }}>
            <header>
              <img src={info?.away_team?.logo} alt="" />
              <span>{info?.away_team?.name_zh}</span>
            </header>
            <table cellspacing={10} cellpadding={10} align='center'>
              <tr className={styles.header}>
                <th>全场</th>
                <th>赛</th>
                <th>胜</th>
                <th>平</th>
                <th>负</th>
                <th>得</th>
                <th>失</th>
                <th>净</th>
                <th>得分</th>
                <th>排名</th>
                <th>胜率</th>
              </tr>
              <tr>
                <td>总</td>
                <TD row={match?.awayIntegrate}></TD>
              </tr>
              <tr>
                <td>主</td>
                <TD row={match?.awayIntegrateInfo?.home}></TD>
              </tr>
              <tr>
                <td>客</td>
                <TD row={match?.awayIntegrateInfo?.away}></TD>
              </tr>
            </table>
          </aside>
        </section>
      </aside>
      <aside>
        <p>近期战绩</p>
        <section>
          <HistoryPanner value="home" teamMatch={match?.asHomeTeamMatch} info={info}></HistoryPanner>
          <HistoryPanner value="away" info={info} teamMatch={match?.asAwayTeamMatch}></HistoryPanner>
        </section>
      </aside>
    </section>
  )
}


const RankingBasketball = ({ match, info, style }) => {
  const home = match?.homeIntegrate
  const away = match?.awayIntegrate

  return (
    <section style={style}>
      <aside>
        <p>联赛排名</p>
        <table borderColor="#E1E1E1" border={1} className={styles.rankingBasketball}>
          <tr>
            <th>球队名称</th>
            <th>胜</th>
            <th>负</th>
            <th>胜率</th>
            <th>主场战绩</th>
            <th>客场胜率</th>
            <th>每场得分</th>
            <th>每场丢分</th>
            <th>连胜/连负</th>
          </tr>
          <tr>
            <td>{info?.homeTeamName}</td>
            <td>{home?.won}</td>
            <td>{home?.lost}</td>
            <td>{((home?.won_rate || 0) * 100) + '%'}</td>
            <td>{home?.home}</td>
            <td>{home?.away}</td>
            <td>{home?.points_avg}</td>
            <td>{home?.points_against_avg}</td>
            <td>{home?.streaks}</td>
          </tr>

          <tr>
            <td>{info?.awayTeamName}</td>
            <td>{away?.won}</td>
            <td>{away?.lost}</td>
            <td>{((away?.won_rate || 0) * 100) + '%'}</td>
            <td>{away?.home}</td>
            <td>{away?.away}</td>
            <td>{away?.points_avg}</td>
            <td>{away?.points_against_avg}</td>
            <td>{away?.streaks}</td>
          </tr>
        </table>
      </aside>

      <aside>
        <p>近期战绩</p>
        <section>
          <HistoryPanner value="home" teamMatch={match?.asHomeTeamMatch} info={info}></HistoryPanner>
          <HistoryPanner value="away" info={info} teamMatch={match?.asAwayTeamMatch}></HistoryPanner>
        </section>
      </aside>
    </section>
  )
}

const Footer = ({ type }) => (
  <>
    <RenderJudge value={type === '1'} active={
      <blockquote className={styles.footer}>
        <p>足球比分直播</p>
        <p>简介：足球比分直播为球迷提供了最快、最全、最准的比分直播，包括竞彩比分直播、足彩即时比分直播、单场即时比分直播、足球即时比分等服务
          ，比分与赛场同步，更有免费的足球联赛直播，包括五大联赛，中超，亚冠，欧洲杯等一系列全面的足球比赛。足球即时比分的数据来自优秀的足球
          比分数据网站，如捷报球足球比分、7m足球比分、球探比分等足球比分网。来球网努力做最好的体育直播网站。</p>
      </blockquote>
    } inactive={
      <blockquote className={styles.footer}>
        <p>篮球比分直播</p>
        <p>简介：篮球比分直播为球迷提供了最快、最全、最准的比分直播，包括竞彩比分直播、足彩即时比分直播、单场即时比分直播、篮球即时比分等服务
          ，比分与赛场同步，更有免费的篮球联赛直播，包括NBA、CBA等一系列全面的篮球比赛。篮球即时比分的数据来自优秀的篮球比分数据网站，如捷
          报篮球比分、7m篮球比分、90VS等篮球比分网。来球网努力做最好的体育直播网站。</p>
      </blockquote>
    } />
  </>

)

const Analysis = ({ fs, type, bs }) => {
  const res = type === process.env.NEXT_PUBLIC_Football ? fs : bs
  console.log(res)
  const [match, info, indexSum] = res

  const text = {
    [process.env.NEXT_PUBLIC_Basketball]: {
      t: "篮球比分,即时比分,NBA比分直播-鑫球体育",
      d: `篮球比分,篮球即时比分,NBA直播,动画直播,文字直播,篮球直播,比分直播,篮球即时比分,篮球比分直播,鑫球体育`,
      k: "鑫球体育篮球比分提供最快的篮球比分直播与篮球文字动画直播，同时提供最准确的篮球分析、即时比分、篮球指数、篮球数据等，看篮球比分就上鑫球体育!"
    },
    [process.env.NEXT_PUBLIC_Football]: {
      t: "足球比分,即时比分,足球比分直播-鑫球体育",
      d: "足球比分,即时比分,足球直播,动画直播,文字直播,足球直播,比分直播,足球即时比分,足球比分直播,鑫球体育",
      k: "鑫球体育足球比分提供最快的足球比分直播与足球文字动画直播，同时提供最准确的足球分析、即时比分、足球指数、足球数据等，看足球比分就上鑫球体育!"
    }
  }
  console.log(indexSum)
  const [selectTab, setSelectTab] = useSafeState(0)
  return (
    <section className={styles.analysis}>
      <Head>
        <title>{Reflect.get(text, type)?.t}</title>
        <meta name='description' content={Reflect.get(text, type)?.d} />
        <meta name="keywords" content={Reflect.get(text, type)?.k} />
      </Head>
      <header>
        <div>
          <p>
            <span>{info?.matchevent?.name_zh}</span>
            <span>{dayjs((info?.info?.matchtime || info?.matchTime) * 1000).format("YYYY/MM/DD HH:mm:ss")}</span>
          </p>
          <section>
            <div>
              <h3>{info?.home_team?.name_zh || info?.homeTeamName}</h3>
              <img src={info?.home_team?.logo || info?.homeTeamLogo} alt={info?.home_team?.name_zh || info?.homeTeamName} />
              <RenderJudge value={type === '1'}
                active={
                  <em>{info?.results?.score?.[2]?.[0]}</em>
                }
                inactive={
                  <em>{info?.homeTeamScore?.reduce((sum, current) => (sum += current), 0)}</em>
                } />
            </div>
            <span>vs</span>
            <div>
              <RenderJudge value={type === '1'} active={
                <em>{info?.results?.score?.[3]?.[0]}</em>
              }
                inactive={
                  <em>{info?.awayTeamScore?.reduce((sum, current) => (sum += current), 0)}</em>
                } />

              <img src={info?.away_team?.logo || info?.awayTeamLogo} alt={info?.away_team?.name_zh || info?.awayTeamName} />
              <h3 style={{ textAlign: "left" }}>{info?.away_team?.name_zh || info?.awayTeamName}</h3>
            </div>
          </section>
          <RenderJudge value={type === '1'} active={
            <h4>{Reflect.get(fState, info?.info?.statusid)}</h4>
          } inactive={
            <h4>{Reflect.get(bState, info?.status)}</h4>
          } />

        </div>
        <nav>
          <div>
            <span className={selectTab === 0 ? styles.active : null} onClick={() => { setSelectTab(0) }}>数据分析</span>
            <span className={selectTab === 1 ? styles.active : null} onClick={() => { setSelectTab(1) }}>指数走势</span>
          </div>
        </nav>
      </header>

      <RenderJudge
        value={type === "1"}
        active={
          <>
            <AnalysisPanner type={type} style={{ display: selectTab === 0 ? 'block' : "none" }} match={match} info={info} />
            <Exponent type={type} indexSum={indexSum} style={{ display: selectTab === 1 ? 'block' : "none" }} />
          </>
        }
        inactive={
          <>
            <AnalysisPanner type={type} style={{ display: selectTab === 0 ? 'block' : "none" }} match={match} info={info} />
            <Exponent type={type} indexSum={indexSum} style={{ display: selectTab === 1 ? 'block' : "none" }} />
          </>
        }
      />
      <Footer type={type} />
    </section>
  )
}

Analysis.getLayout = (page) => {
  return (
    <Page header footer >
      {page}
    </Page >
  )
}


export async function getServerSideProps (ctx) {

  const type = ctx?.params?.id[0]
  const id = ctx?.params?.id[1]
  let fs = []
  let bs = []
  if (type === process.env.NEXT_PUBLIC_Football) {
    fs = await Promise.all([getFootballAnalysis(id), getFootballStatistics(id), getFootballIndexSum(id)])
  }
  if (type === process.env.NEXT_PUBLIC_Basketball) {
    bs = await Promise.all([getBasketballAnalysis(id), getBasketballDetail(id), getBasketballIndexSum(id)])
  }
  console.log(bs[0])
  // console.log(fs)
  return {
    props: {
      fs,
      type,
      bs
    }
  }
}


export default Analysis